package edu.cmu.cs211.exprtree.ast;

import java.math.BigDecimal;
import java.math.MathContext;

public final class BigDecimalUtils {
	BigDecimalUtils () {
	}

	/**
	 * Tests if two {@link BigDecimal} objects are equal in numerical value.
	 */
	public static boolean areEqual (BigDecimal a, BigDecimal b)
	{
		return a.compareTo (b) == 0;
	}

	/**
	 * Tests if a {@link BigDecimal} is equal to 1 in numerical value.
	 */
	public static boolean isOne (BigDecimal x)
	{
		return areEqual (x, BigDecimal.ONE);
	}

	/**
	 * Tests if a {@link BigDecimal} is equal to 0 in numerical value.
	 */
	public static boolean isZero (BigDecimal x)
	{
		return areEqual (x, BigDecimal.ZERO);
	}

	/**
	 * Tests if a {@link BigDecimal} is equal to -1 in numerical value.
	 */
	public static boolean isMinusOne (BigDecimal x)
	{
		return areEqual (x, BigDecimal.ONE.negate ());
	}

	/**
	 * Safely divides two {@link BigDecimal} objects without the risk of an
	 * {@link ArithmeticException} in the case that an exact result can't be
	 * computed.
	 */
	public static BigDecimal safeDivide (BigDecimal dividend, BigDecimal divisor)
	{
		return dividend.divide (divisor, MathContext.DECIMAL32);
	}
}
